﻿using System.Data;
using Common;
using MySql.Data.MySqlClient;

namespace DAL
{
    public class MySqlHelper
    {
        public static MySqlHelper Instance = SingleTon<MySqlHelper>.Instance;

        public static string ConnStr { get; private set; }

        public MySqlHelper()
        {
            ConnStr = Properties.Settings.Default.ConnStr;
        }

        public MySqlConnection GetConnection()
        {
            MySqlConnection conn = new MySqlConnection(ConnStr);
            conn.Open();
            return conn;
        }

        public int ExecuteNonQuery(string sql)
        {
            using (MySqlConnection conn = GetConnection())
            {
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        public bool ExecuteSql(string sql)
        {
            return ExecuteNonQuery(sql) >= 0;
        }

        public DataSet GetDataSet(string sql)
        {
            using (MySqlConnection conn = GetConnection())
            {
                using (MySqlDataAdapter da = new MySqlDataAdapter(sql, conn))
                {
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    return ds;
                }
            }
        }

        public MySqlDataReader GetReader(string sql)
        {
            using (MySqlConnection conn = GetConnection())
            {
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    return cmd.ExecuteReader();
                }
            }
        }

        public DataTable GetTable(string sql)
        {
            using (MySqlConnection conn = GetConnection())
            {
                using (MySqlDataAdapter da = new MySqlDataAdapter(sql, conn))
                {
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    return dt;
                }
            }
        }
    }
}
